﻿using ruleEngineDemo.engine.factory.product;
using ruleEngineDemo.engine.viewmodel;
using RulesEngine.Models;
using System.Dynamic;

namespace ruleEngineDemo.engine.rulesengine.product
{
    /// <summary>
    /// 基础rules演示
    /// </summary>
    public class BasicRules : IBasicRules
    {
        /// <summary>
        /// 执行rules
        /// </summary>
        /// <returns></returns>
        public RulesResult Run()
        {
            List<Workflow> workflows = new List<Workflow>();
            Workflow workflow = new Workflow();
            workflow.WorkflowName = "Test Workflow Rule 1";

            List<Rule> rules = new List<Rule>();

            Rule rule = new Rule();
            rule.RuleName = "Test Rule";
            rule.SuccessEvent = "Count is within tolerance.";
            rule.ErrorMessage = "Over expected.";
            rule.Expression = "count < 3";
            rule.RuleExpressionType = RuleExpressionType.LambdaExpression;

            rules.Add(rule);

            workflow.Rules = rules;

            workflows.Add(workflow);

            var bre = new RulesEngine.RulesEngine(workflows.ToArray(), null);

            dynamic datas = new ExpandoObject();
            datas.count = 1;
            var inputs = new dynamic[]
              {
                    datas
              };

            List<RuleResultTree> resultList = bre.ExecuteAllRulesAsync("Test Workflow Rule 1", inputs).Result;

            RulesResult rRt = new RulesResult
            {
                IsPass = true,
                Errors = new List<string>()
            };
            foreach(var item in resultList)
            {
                if(item.IsSuccess==false)
                {
                    rRt.IsPass = false;
                    rRt.Errors.Add($"Failed: {item.Rule.RuleName}");
                }
            }
            return rRt;
        }
    }
}
